<template>
  <view class="student-auth-page">
    <!-- 顶部导航栏 -->
    <tn-nav-bar fixed :isBack="true" backgroundColor="#ffffff" :bottomShadow="false" @click-back="navBack"
      backIconColor="#0057b8" title="在校生认证"></tn-nav-bar>

    <!-- 内容区域 -->
    <view class="content">
      <view class="form-item">
        <view class="label required">真实姓名 <text class="required-mark">*</text></view>
        <input class="input" placeholder="请输入真实姓名" v-model="form.realName" />
      </view>

      <view class="form-item">
        <view class="label required">性别 <text class="required-mark">*</text></view>
        <view class="gender-select">
          <radio-group v-model="form.gender">
            <label class="radio-label">
              <radio value="0" /> 男
            </label>
            <label class="radio-label">
              <radio value="1" /> 女
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-item">
        <view class="label required">微信号 <text class="required-mark">*</text></view>
        <input class="input" placeholder="请输入微信号" v-model="form.wechatId" />
      </view>

      <view class="form-item">
        <view class="label required">身份证正面 <text class="required-mark">*</text></view>
        <view class="id-card-upload" @click="uploadIdCard('front')">
          <view class="upload-tip" v-if="!form.idCardFront">点击上传本地图片</view>
          <image v-else :src="form.idCardFront" mode="aspectFill" class="upload-img"></image>
        </view>
      </view>

      <view class="form-item">
        <view class="label required">身份证反面 <text class="required-mark">*</text></view>
        <view class="id-card-upload" @click="uploadIdCard('back')">
          <view class="upload-tip" v-if="!form.idCardBack">点击上传本地图片</view>
          <image v-else :src="form.idCardBack" mode="aspectFill" class="upload-img"></image>
        </view>
      </view>

      <view class="form-item">
        <view class="label required">所在学院 <text class="required-mark">*</text></view>
        <picker mode="selector" :range="colleges" :range-key="'name'" @change="handleCollegeChange" class="picker">
          <view class="picker-text">{{ form.collegeName || '请选择学院' }}</view>
        </picker>
      </view>

      <view class="form-item">
        <view class="label required">专业 <text class="required-mark">*</text></view>
        <input class="input" placeholder="请输入专业" v-model="form.major" />
      </view>

      <view class="submit-btn">
        <button class="btn" :loading="submitting" @click="submitAuth">提交认证</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      submitting: false,
      form: {
        realName: '',
        gender: '0',
        wechatId: '',
        idCardFront: '',
        idCardBack: '',
        college: '',
        collegeName: '',
        major: ''
      },
      colleges: [
        { code: '1', name: '电气与信息工程学院' },
        { code: '2', name: '经济管理学院' },
        { code: '3', name: '商学院' },
        { code: '4', name: '文学院' },
        { code: '5', name: '法学院' }
      ]
    }
  },
  methods: {
    navBack() {
      uni.navigateBack({ delta: 1 });
    },

    handleCollegeChange(e) {
      const selected = this.colleges[e.detail.value];
      this.form.college = selected.code;
      this.form.collegeName = selected.name;
    },

    // 统一处理身份证正反面上传（移除格式限制）
    uploadIdCard(type) {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (chooseRes) => {
          const tempFilePath = chooseRes.tempFilePaths[0];

          uni.uploadFile({
            url: 'http://8.152.193.84/api/upload/image',
            filePath: tempFilePath,
            name: 'file',
            header: {
              'content-type': 'multipart/form-data'
            },
            success: (uploadRes) => {
              const result = JSON.parse(uploadRes.data);
              if (result.code === 200 && result.data) {
                if (type === 'front') {
                  this.form.idCardFront = result.data;
                } else {
                  this.form.idCardBack = result.data;
                }
              } else {
                uni.showToast({ title: '图片上传失败', icon: 'none' });
              }
            },
            fail: (err) => {
              console.error('图片上传失败：', err);
              uni.showToast({ title: '网络异常，图片上传失败', icon: 'none' });
            }
          });
        },
        fail: (err) => {
          console.log('选择图片失败：', err);
          uni.showToast({ title: '图片选择失败，请重试', icon: 'none' });
        }
      });
    },

    validateForm() {
      if (!this.form.realName) {
        uni.showToast({ title: '请输入真实姓名', icon: 'none' });
        return false;
      }
      if (!this.form.wechatId) {
        uni.showToast({ title: '请输入微信号', icon: 'none' });
        return false;
      }
      if (!this.form.idCardFront) {
        uni.showToast({ title: '请上传身份证正面', icon: 'none' });
        return false;
      }
      if (!this.form.idCardBack) {
        uni.showToast({ title: '请上传身份证反面', icon: 'none' });
        return false;
      }
      if (!this.form.college) {
        uni.showToast({ title: '请选择学院', icon: 'none' });
        return false;
      }
      if (!this.form.major) {
        uni.showToast({ title: '请输入专业', icon: 'none' });
        return false;
      }
      return true;
    },

    submitAuth() {
      if (!this.validateForm()) return;
      this.submitting = true;

      const submitData = {
        realName: this.form.realName,
        gender: Number(this.form.gender),
        wechatId: this.form.wechatId,
        idCardFront: this.form.idCardFront,
        idCardBack: this.form.idCardBack,
        college: this.form.college,
        major: this.form.major,
        idStatus: 0
      };

      uni.request({
        url: 'http://8.152.193.84/api/users/add',
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: submitData,
        success: (res) => {
          const result = res.data || {};
          if (result.code === 200) {
            uni.showToast({ title: '提交成功，等待审核', icon: 'success' });
            setTimeout(() => {
              this.navBack();
            }, 1500);
          } else {
            uni.showToast({ title: result.msg || '提交失败，请重试', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error('接口调用失败：', err);
          uni.showToast({ title: '网络异常，提交失败', icon: 'none' });
        },
        complete: () => {
          this.submitting = false;
        }
      });
    }
  }
}
</script>

<style scoped>
.student-auth-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: 88rpx;
}

.content {
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
  display: block;
}

.required {
  position: relative;
}

.required-mark {
  color: #ff4d4f;
  margin-left: 4rpx;
  font-size: 32rpx;
}

.input {
  width: 100%;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 32rpx;
  color: #333;
  border-bottom: 1rpx solid #eee;
}

.picker {
  width: 100%;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 32rpx;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #eee;
}

.picker-text {
  flex: 1;
}

.gender-select {
  display: flex;
  gap: 40rpx;
}

.radio-label {
  display: flex;
  align-items: center;
  font-size: 32rpx;
  color: #333;
}

radio {
  margin-right: 12rpx;
}

.id-card-upload {
  border: 1rpx dashed #ddd;
  border-radius: 8rpx;
  height: 240rpx;
  padding: 20rpx;
  text-align: center;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
}

.id-card-upload:active {
  border-color: #007356;
}

.upload-tip {
  font-size: 28rpx;
  color: #999;
  margin: 0;
}

.upload-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8rpx;
}

.submit-btn {
  margin-top: 40rpx;
}

.btn {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  background: linear-gradient(45deg, #008662, #007356);
  color: #fff;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 500;
  box-shadow: 0 4rpx 16rpx rgba(54, 144, 250, 0.2);
  border: none;
}

.btn[loading] {
  background: linear-gradient(90deg, #409eff, #3690fa);
  opacity: 0.9;
}
</style>